package kr.co.dongpang.android;

import java.io.File;
import java.util.ArrayList;

import com.squareup.picasso.Picasso;
import com.sys.app.cms.AndroidCustomGalleryActivity2;
import com.sys.app.cms.ImageInfo;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.GridView;
import android.widget.TextView;

public class DmGalleryCategory extends Activity {

	GridView gridView;
	ArrayList<MyData> datas = new ArrayList<MyData>();
	MyAdapter adapter;

	private static final int PICK_FROM_MULTI_ALBUM = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_gallery);

		gridView = (GridView) findViewById(R.id.galleryCategory);
		adapter = new MyAdapter(null, 0);
		gridView.setAdapter(adapter);

		getGalleryCategory();
	}

	class MyAdapter extends ArrayAdapter<MyData> {

		public MyAdapter(Context context, int resource) {
			super(DmGalleryCategory.this, R.layout.new_gallery_row, datas);
			// TODO Auto-generated constructor stub
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub

			if (convertView == null) {
				convertView = DmGalleryCategory.this.getLayoutInflater().inflate(R.layout.new_gallery_row, null);
			}

			final MyData myData = datas.get(position);
			((TextView) convertView.findViewById(R.id.categoryName)).setText(myData.categoryName + "\n(" + myData.count + ")");
//			ImageView imageView = (ImageView) convertView.findViewById(R.id.imageView);
//			Picasso.with(getApplicationContext()).load(Uri.fromFile(new File(myData.photoUri))).into(imageView);

			convertView.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(DmGalleryCategory.this, AndroidCustomGalleryActivity2.class);
					intent.putExtra("categoryName", myData.categoryName);
					intent.putExtra("categoryCount", String.valueOf(myData.count));
					startActivityForResult(intent, PICK_FROM_MULTI_ALBUM);
				}
			});

			return convertView;
		}

	}

	class MyData {
		public File[] fileList;
		public String categoryName;
		public String photoUri;
		public int count;
	}

	public void getGalleryCategory() {
		String[] projection = new String[] { "DISTINCT " + MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME };
		Cursor cur = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null, null, null);

		while (cur.moveToNext()) {
			String bucket = cur.getString((cur.getColumnIndex(MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME)));
			MyData img = new MyData();

			img.categoryName = bucket;
			img.count = photoCountByAlbum(bucket);
			img.photoUri = "";

			datas.add(img);
		}

		adapter.notifyDataSetChanged();

	}

	private int photoCountByAlbum(String bucketname) {
		try {
			final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
			String searchParams = null;
			String bucket = bucketname;
			searchParams = "bucket_display_name = \"" + bucket + "\"";

			Cursor mPhotoCursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, searchParams, null,
					orderBy + " DESC");

			if (mPhotoCursor.getCount() > 0) {
				return mPhotoCursor.getCount();
			}

			mPhotoCursor.close();

		} catch (Exception e) {
			e.printStackTrace();
		}

		return 0;

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.

		switch (item.getItemId()) {
		case android.R.id.home:
			onBackPressed();
			break;
		default:
			return super.onOptionsItemSelected(item);
		}
		return true;

	}


	ArrayList<ImageInfo> selectImages;
	
	@SuppressWarnings("unchecked")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode != RESULT_OK) {
			return;
		}

		switch (requestCode) {

			case PICK_FROM_MULTI_ALBUM: {

					Log.d("","resultCode:::");

					selectImages = (ArrayList<ImageInfo>) data.getExtras().getSerializable("selectImages");
					
					
					if (selectImages.size() == 0) {
						return;
					}
					
					Log.d("","selectImages:si:"+selectImages);
					
					Intent intent = new Intent();

					Bundle extra = new Bundle();
					extra.putSerializable("selectImages", selectImages);
					intent.putExtras(extra);
					
					setResult(RESULT_OK, intent);
					finish();				
					
	
				break;
			}

		}
	}

}
